
package com.trial.area.permission.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.trial.area.common.controller.BaseController;
import com.trial.area.common.param.SessionAdminUser;
import com.trial.area.common.param.SessionUserInfo;
import com.trial.area.config.ConfigUtils;
import com.trial.area.permission.entity.AdminUserVO;
import com.trial.area.permission.entity.RoleVO;
import com.trial.area.permission.param.AdminUserParam;
import com.trial.area.permission.param.UserRoleParam;
import com.trial.area.permission.service.AdminUserService;
import com.trial.area.permission.service.PermissionService;
import com.trial.area.permission.service.RoleService;
import com.trial.area.permission.service.UserRoleService;
import com.trial.area.user.entity.UserInfoVO;
import com.trial.area.user.service.UserInfoService;

/**
 * 管理员用户信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class AdminUserController extends BaseController {
    
    private Logger logger = LoggerFactory.getLogger(AdminUserController.class);
    
    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserInfoService userInfoService;
    
    @Autowired
    private AdminUserService adminUserService;
    
    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;
    
    private final static String ACCOUNT_LIST_PAGE = "/base/adminuser/admin_user_list";
    
    private final static String USER_ROLE_LIST_PAGE = "/base/adminuser/user_role_list";
    
    private final static String ACCOUNT_EDIT_PAGE = "/base/adminuser/admin_user_edit";
    
    private final static String ACCOUNT_VIEW_PAGE = "/base/adminuser/admin_user_view";
    
    private final static String RESET_PASSWORD_PAGE = "/base/adminuser/reset_my_password";
    
    private final static String LOGIN_PAGE = "/admin/login";

    private static final String INDEX_PAGE = "/admin/admin_center";
    
    @RequestMapping(value = "/uncheck/adminLogin")
    public ModelAndView login(String redirectUrl) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("redirectUrl", redirectUrl);
        return new ModelAndView(LOGIN_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/doAdminLogin", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String doLogin(String userAccount, String userPassword, String imageCode) {
        JSONObject result = new JSONObject();
        
        if (StringUtils.isBlank(userPassword) || StringUtils.isBlank(userAccount)) {
            result.put("result", false);
            result.put("msg", "用户名或密码不能为空");
            return result.toString();
        }
        
        AdminUserVO adminUserVO = adminUserService.queryByAccount(userAccount);
        if (adminUserVO == null) {
            result.put("result", false);
            result.put("msg", "用户不存在");
            return result.toString();
        }
        
        if (StringUtils.equals(userPassword, adminUserVO.getUserPassword())) {
            SessionAdminUser sessionAdminUser = new SessionAdminUser();
            String adminUserId = adminUserVO.getAdminUserId();
            sessionAdminUser.setAdminUserId(adminUserId);
            sessionAdminUser.setUserName(adminUserVO.getUserName());
            
            sessionAdminUser.setAdminUser(adminUserVO);
            
            sessionAdminUser.setPermissionList(permissionService.queryPermissionByUserId(adminUserId));
            sessionAdminUser.setRoleList(roleService.queryRoleByUserId(adminUserId));
            
            session.setAttribute("sessionAdminUser", sessionAdminUser);
            result.put("result", true);
            result.put("msg", "成功");

            if (StringUtils.isNotBlank(adminUserVO.getUserId())) {
                // 根据Userid获取注册过的用户信息
                UserInfoVO user = userInfoService.findById(adminUserVO.getUserId(), null, null);

                if (user != null) {
                    String userId = user.getUserId();
                    // 刷新session
                    SessionUserInfo seUser = new SessionUserInfo();
                    seUser.setUserId(userId);
                    seUser.setUserName(user.getNickName());
                    seUser.setUserInfo(user);
                    session.setAttribute("sessionUserInfo", seUser);
                }
            }
            
            return result.toString();
        } else {
            result.put("result", false);
            result.put("msg", "用户名或密码错误");
            return result.toString();
        }
    }
    
    @RequestMapping(value = "/admin/adminLogout")
    public ModelAndView logout() {
        session.removeAttribute("sessionAdminUser");
        return new ModelAndView(INDEX_PAGE);
    }

    @RequestMapping(value = "/admin/adminUser/toResetMyPassword")
    public ModelAndView toResetPassword() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        return new ModelAndView(RESET_PASSWORD_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/adminUser/resetMyPassword", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String resetMyPassword(String newPassword, String rePassword) {
        AdminUserVO adminUserVO = new AdminUserVO();
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        if (StringUtils.isBlank(newPassword)) {
            resultMap.put("result", false);
            resultMap.put("message", "修改密码时,新密码不能为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        if (!StringUtils.equals(newPassword, rePassword)) {
            resultMap.put("result", false);
            resultMap.put("message", "修改密码时,两次输入的密码不一致");
            return JSONObject.toJSONString(resultMap);
        }
        
        try {
            SessionAdminUser sessionAdminUser = (SessionAdminUser) session.getAttribute("sessionAdminUser");
            adminUserVO.setUserPassword(newPassword);
            adminUserVO.setAdminUserId(sessionAdminUser.getAdminUserId());
            
            if (StringUtils.isBlank(adminUserVO.getAdminUserId())) {
                resultMap.put("result", false);
                resultMap.put("message", "修改密码时管理员用户ID不能为空");
                return JSONObject.toJSONString(resultMap);
            }
            
            Integer insertCount = adminUserService.update(adminUserVO);
            if (insertCount != null && insertCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "修改管理员用户密码成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "修改管理员用户密码失败");
            }
        } catch (Exception e) {
            logger.error("修改管理员用户密码出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "修改管理员用户密码出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/toInsert")
    public ModelAndView intoInsert() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        AdminUserVO adminUserVO = new AdminUserVO();
        adminUserVO.setUserPassword(ConfigUtils.getStringValueByKey("default_admin_user_password"));
        resultMap.put("adminUserVO", adminUserVO);
        return new ModelAndView(ACCOUNT_EDIT_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        AdminUserVO adminUserVO = adminUserService.findById(id);
        resultMap.put("adminUserVO", adminUserVO);
        return new ModelAndView(ACCOUNT_EDIT_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(AdminUserVO adminUserVO) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (adminUserVO == null) {
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改用户信息失败,用户信息为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        if (StringUtils.isBlank(adminUserVO.getUserAccount())) {
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改用户信息时,用户账号不能为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        if (StringUtils.isBlank(adminUserVO.getUserName())) {
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改用户信息时,用户姓名不能为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        AdminUserVO oldAdminUser = adminUserService.queryByAccount(adminUserVO.getUserAccount());
        
        if (StringUtils.isBlank(adminUserVO.getAdminUserId())) {
            if (oldAdminUser != null && StringUtils.isNotBlank(oldAdminUser.getAdminUserId())) {
                resultMap.put("result", false);
                resultMap.put("message", "新增用户信息时,该账号已存在");
                return JSONObject.toJSONString(resultMap);
            }
        } else {
            if (oldAdminUser != null && !StringUtils.equals(adminUserVO.getAdminUserId(), oldAdminUser.getAdminUserId())) {
                resultMap.put("result", false);
                resultMap.put("message", "修改用户信息时,该账号已存在");
                return JSONObject.toJSONString(resultMap);
            }
        }
        
        try {
            Integer insertCount = adminUserService.update(adminUserVO);
            if (insertCount != null && insertCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改用户信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改用户信息失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改用户信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改用户信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/view/{id}")
    public ModelAndView view(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        AdminUserVO adminUserVO = adminUserService.findById(id);
        resultMap.put("adminUserVO", adminUserVO);
        return new ModelAndView(ACCOUNT_VIEW_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/resetPassword", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String resetPassword(String adminUserId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        AdminUserVO adminUserVO = new AdminUserVO();

        adminUserVO.setAdminUserId(adminUserId);
        adminUserVO.setUserPassword(ConfigUtils.getStringValueByKey("default_admin_user_password"));
        
        if (StringUtils.isBlank(adminUserVO.getAdminUserId())) {
            resultMap.put("result", false);
            resultMap.put("message", "重置密码时管理员用户ID不能为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        try {
            Integer insertCount = adminUserService.update(adminUserVO);
            if (insertCount != null && insertCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "重置管理员用户密码成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "重置管理员用户密码失败");
            }
        } catch (Exception e) {
            logger.error("修改管理员用户密码出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "重置管理员用户密码出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = adminUserService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除管理员用户信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除管理员用户信息失败");
            }
        } catch (Exception e) {
            logger.error("删除管理员用户信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除管理员用户信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/accountList")
    public ModelAndView accountList(AdminUserParam paramMap) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<AdminUserVO> dataList = adminUserService.queryByPage(paramMap);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", paramMap);
        return new ModelAndView(ACCOUNT_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/userRoleList")
    public ModelAndView userRoleList(UserRoleParam paramMap) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        List<RoleVO> dataList = userRoleService.queryUserRoleList(paramMap);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", paramMap);
        return new ModelAndView(USER_ROLE_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/insertUserRole", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String insertUserRole(String adminUserId, String roleId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        if (StringUtils.isBlank(adminUserId)) {
            resultMap.put("result", false);
            resultMap.put("message", "用户ID不能为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        if (StringUtils.isBlank(roleId)) {
            resultMap.put("result", false);
            resultMap.put("message", "角色ID不能为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        try {
            Integer effectNum = userRoleService.insertUserRole(adminUserId, roleId);
            if (effectNum > 0) {
                resultMap.put("result", true);
                resultMap.put("message", "修改用户权限成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "修改用户权限失败");
            }
        } catch (Exception e) {
            logger.error("修改用户权限出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "修改用户权限出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/base/adminUser/deleteUserRole", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String deleteUserRole(String adminUserId, String roleId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        if (StringUtils.isBlank(adminUserId)) {
            resultMap.put("result", false);
            resultMap.put("message", "用户ID不能为空");
            return JSONObject.toJSONString(resultMap);
        }
        
        try {
            Integer deleteCount = userRoleService.deleteById(adminUserId, roleId);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除用户角色成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除用户角色失败");
            }
        } catch (Exception e) {
            logger.error("删除用户角色出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除用户角色出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
}
